package com.apigen.platform.controller;

import com.apigen.platform.common.Result;
import com.apigen.platform.dto.CaptchaResponse;
import com.apigen.platform.dto.LoginRequest;
import com.apigen.platform.dto.LoginResponse;
import com.apigen.platform.security.UserPrincipal;
import com.apigen.platform.service.IAuthService;
import com.apigen.platform.service.ICaptchaService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 认证控制器
 *
 * @author API Generator Platform
 * @since 2025-09-24
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@Validated
@Tag(name = "认证管理", description = "用户登录、登出、Token刷新等认证相关接口")
public class AuthController {

    private final IAuthService authService;
    private final ICaptchaService captchaService;

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "通过账户名和密码进行用户登录")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            LoginResponse response = authService.login(loginRequest);
            return Result.success(response);
        } catch (Exception e) {
            log.error("用户登录失败: {}", e.getMessage());
            return Result.error("登录失败: " + e.getMessage());
        }
    }

    @PostMapping("/refresh")
    @Operation(summary = "刷新Token", description = "使用刷新令牌获取新的访问令牌")
    public Result<LoginResponse> refreshToken(
            @Parameter(description = "刷新令牌") 
            @RequestParam String refreshToken) {
        try {
            LoginResponse response = authService.refreshToken(refreshToken);
            return Result.success(response);
        } catch (Exception e) {
            log.error("Token刷新失败: {}", e.getMessage());
            return Result.error("Token刷新失败: " + e.getMessage());
        }
    }

    @PostMapping("/logout")
    @Operation(summary = "用户登出", description = "用户退出登录，清除服务器端Token缓存")
    public Result<Void> logout() {
        try {
            UserPrincipal currentUser = getCurrentUser();
            if (currentUser != null) {
                authService.logout(currentUser.getUserId());
            }
            return Result.success("退出登录成功");
        } catch (Exception e) {
            log.error("用户登出失败: {}", e.getMessage());
            return Result.error("退出登录失败: " + e.getMessage());
        }
    }

    @GetMapping("/me")
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的详细信息")
    public Result<LoginResponse.UserInfo> getCurrentUserInfo() {
        try {
            UserPrincipal currentUser = getCurrentUser();
            if (currentUser == null) {
                return Result.error("用户未登录");
            }
            
            LoginResponse.UserInfo userInfo = authService.getCurrentUserInfo(currentUser.getUserId());
            return Result.success(userInfo);
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage());
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }

    @GetMapping("/check")
    @Operation(summary = "检查登录状态", description = "检查当前用户的登录状态")
    public Result<Boolean> checkLoginStatus() {
        UserPrincipal currentUser = getCurrentUser();
        boolean isLoggedIn = currentUser != null;
        return Result.success(isLoggedIn);
    }

    @GetMapping("/captcha")
    @Operation(summary = "获取验证码", description = "生成图片验证码用于登录验证")
    public Result<CaptchaResponse> getCaptcha() {
        try {
            CaptchaResponse captcha = captchaService.generateCaptcha();
            return Result.success(captcha);
        } catch (Exception e) {
            log.error("获取验证码失败: {}", e.getMessage());
            return Result.error("获取验证码失败: " + e.getMessage());
        }
    }

    @PostMapping("/captcha/refresh")
    @Operation(summary = "刷新验证码", description = "刷新现有的验证码")
    public Result<CaptchaResponse> refreshCaptcha(
            @Parameter(description = "验证码ID") @RequestParam(required = false) String captchaId) {
        try {
            CaptchaResponse captcha = captchaService.refreshCaptcha(captchaId);
            return Result.success(captcha);
        } catch (Exception e) {
            log.error("刷新验证码失败: {}", e.getMessage());
            return Result.error("刷新验证码失败: " + e.getMessage());
        }
    }

    @PostMapping("/captcha/validate")
    @Operation(summary = "验证验证码", description = "验证用户输入的验证码是否正确")
    public Result<Boolean> validateCaptcha(
            @Parameter(description = "验证码ID") @RequestParam String captchaId,
            @Parameter(description = "验证码") @RequestParam String captchaCode) {
        try {
            boolean isValid = captchaService.validateCaptcha(captchaId, captchaCode);
            return Result.success(isValid);
        } catch (Exception e) {
            log.error("验证验证码失败: {}", e.getMessage());
            return Result.error("验证验证码失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前登录用户
     */
    private UserPrincipal getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserPrincipal) {
            return (UserPrincipal) authentication.getPrincipal();
        }
        return null;
    }
}











